package com.vxdata.utils.modules.utils.smzx;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 基于 hutool CacheUtil 的本地缓存工具类
 */
public class LocalCacheUtil {
    // 默认缓存时长，单位为分钟
    private static final long DEFAULT_TIMEOUT_MINUTES = 5;
    // 默认缓存时长，转换为毫秒
    private static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(DEFAULT_TIMEOUT_MINUTES);

    // 缓存对象，使用Hutool的TimedCache实现
    private static final TimedCache<String, Object> TIMED_CACHE = CacheUtil.newTimedCache(DEFAULT_TIMEOUT_MILLIS);

    // 设置缓存，使用默认过期时间
    public static void set(String key, Object value) {
        TIMED_CACHE.put(key, value);
    }

    // 设置缓存，指定过期时间，单位为分钟
    public static void set(String key, Object value, long expireMinutes) {
        // 将过期时间转换为毫秒
        long expireMillis = TimeUnit.MINUTES.toMillis(expireMinutes);
        // 设置缓存
        TIMED_CACHE.put(key, value, expireMillis);
    }

    // 获取缓存值
    public static Object get(String key) {
        return TIMED_CACHE.get(key, false);
    }

    // 获取缓存键集合
    public static Set<String> keySet() {
        return TIMED_CACHE.keySet();
    }

    // 移除缓存
    public static void remove(String key) {
        TIMED_CACHE.remove(key);
    }

    // 清空缓存
    public static void clear() {
        TIMED_CACHE.clear();
    }

    public static void main(String[] args) {
        LocalCacheUtil.set("key", "value");
        System.out.println(LocalCacheUtil.get("key"));
        LocalCacheUtil.set("key", "keyV");
        System.out.println(LocalCacheUtil.get("key"));
        LocalCacheUtil.set("key2", "value2", 1);
        System.out.println("++++++++++++++++++++++++++++++");
        System.out.println(LocalCacheUtil.keySet());
        LocalCacheUtil.remove("key");
        System.out.println(LocalCacheUtil.keySet());
        LocalCacheUtil.clear();
        System.out.println("++++++++++++++++++++++++++++++");
        System.out.println("清除之后: " + LocalCacheUtil.keySet());
    }
}
